﻿using Abp.Domain.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using Yozeev.BusinessLogic;
using Yozeev.BusinessLogic.Stats.Dtos;

namespace Yozeev.Controllers.Stats.Oper
{
    /// <summary>
    /// 统计收入和游客数量
    /// </summary>
    public class RevenueAnalytics : IRevenueAnalytics
    {
        private readonly IRepository<Activity, Guid> _activityRep;

        public RevenueAnalytics(IRepository<Activity, Guid> activityRep)
        {
            _activityRep = activityRep;
        }

        public RevenueAnalyticsResultDto Analycis(ITimeSpan timespan, string date, int dataCount)
        {
            IQueryable<Activity> activities = timespan.GetActivities(date);

            var query = timespan.Query(activities);

            var dicFinance = new Dictionary<string, decimal>();
            var dicCustomer = new Dictionary<string, int>();
            var timeSpan = query.Select(q => q.Hours).ToList();
            var financeAmounts = query.Select(q => q.TotalAmount).ToList();
            var quantity = query.Select(q => q.TotalQuantity).ToList();
            int startPoint = dataCount == 12 ? 1 : (dataCount == 30 ? 1 : 0);
            for (var i = startPoint; i < dataCount; i++)
            {
                if (timeSpan.Contains(i))
                {
                    dicFinance.Add(timeSpan[timeSpan.IndexOf(i)].ToString(), financeAmounts[timeSpan.IndexOf(i)]);
                    dicCustomer.Add(timeSpan[timeSpan.IndexOf(i)].ToString(), (int)quantity[timeSpan.IndexOf(i)]);
                }
                else
                {
                    dicFinance.Add(i.ToString(), new decimal(0));
                    dicCustomer.Add(i.ToString(), 0);
                }
            }

            var result = new RevenueAnalyticsResultDto
            {
                FinanceAnal = new RevenueAnalyticsResultDto.FinanceAnalytics
                {
                    TimeSpan = dicFinance.Keys.ToList(),
                    Amount = dicFinance.Values.ToList(),
                    TotalAmount = dicFinance.Values.Sum()
                },
                CustomerAnal = new RevenueAnalyticsResultDto.CustomerAnalytics
                {
                    TimeSpan = dicCustomer.Keys.ToList(),
                    Count = dicCustomer.Values.ToList(),
                    TotalCount = dicCustomer.Values.Sum()
                }
            };

            return result;
        }
    }
}
